//
//  mainViewController.swift
//  weather
//
//  Created by 陈思斌 on 21/8/17.
//  Copyright © 2017年 陈思斌. All rights reserved.
//

import UIKit
import CoreLocation
class MainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate {
    var myTableView :UITableView!
    let header = MJRefreshNormalHeader()
    var currentWeatherInfo : WeatherInfo!
    var locationManager:CLLocationManager!
    var currentCity:String!
    var hud:MBProgressHUD!
    var rootController: UIViewController?
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(autoLocation), name: NSNotification.Name(rawValue: AutoLocationNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(chooseLocationCity), name: NSNotification.Name(rawValue:ChooseLocationCityNotification), object: nil)
        self.navigationController?.navigationBar.isHidden = true
        self.view.backgroundColor = UIColor.black
        
//        定位之前的加载动画
        let myCity = UserDefaults.standard.object(forKey: currentCityKey)
        self.hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        
        if myCity == nil{
            self.myLocation()
        }else{
            self.currentCity = myCity as! String
            self.initView()
        }
       
        
        
    }
    func chooseLocationCity(sender:Notification){
        self.currentCity = sender.userInfo?["choose_city"] as! String
        Helper.insertCity(city: self.currentCity)
        self.initView()
    }
    func autoLocation(sender:Notification){
        self.myLocation()
    }
    
    func myLocation(){
        if CLLocationManager .locationServicesEnabled() {
           
            self.locationManager = CLLocationManager()
            self.locationManager.delegate = self
            self.locationManager.startUpdatingLocation()
            if #available(iOS 8.0, *){
                self.locationManager.requestWhenInUseAuthorization()
                if #available(iOS 9.0, *){
                    self.locationManager.stopUpdatingLocation()
                    
                    //  不能与 startUpdatingLocation同时使用
                    // 必须实现代理的定位失败的方法
                    locationManager.requestLocation()
                    
                    // 在ios9.0以后, 想要在后台获取用户位置,
                    // 前台定位授权, 那么你必须勾选后台模式 location updates,同时设置allowsBackgroundLocationUpdates为true
                    self.locationManager.allowsBackgroundLocationUpdates = true
                }
            }else{
                self.locationManager.requestAlwaysAuthorization()
            }
        }

        
        
    }
  
    //定位失败
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        
        if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) {
            if( CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .notDetermined ){
                let alertCon = UIAlertController.init(title: "端末位置坐标没有被允许，引导用户去设置打开坐标", message: nil, preferredStyle: .alert)
                
                let cancelAction = UIAlertAction.init(title: " 取消", style: .cancel, handler: nil)
                let okAction = UIAlertAction.init(title: "设定", style: .default, handler: { (action) in
                    UIApplication.shared.openURL(appSettings as URL)
                })
                
                alertCon.addAction(cancelAction)
                alertCon.addAction(okAction)
                self.present(alertCon, animated: true, completion: nil)
            }
        }
    }
    //定位成功
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.hud.label.text = "正在定位"
        if locations.count > 0{
            self.locationManager.stopUpdatingLocation()
            let locationInfo = locations.first
            let geoCoder = CLGeocoder()
            geoCoder.reverseGeocodeLocation(locationInfo!, completionHandler: { (placeMarks, error) in
                if error == nil{
                    let pl = placeMarks!.first!
                    self.currentCity = pl.locality!
                    if self.currentCity.hasSuffix("市"){
                        self.currentCity.removeSubrange((self.currentCity?.range(of: "市"))!)
                        self.hud.label.text = "定位成功，正在读取天气信息"
                        Helper.insertCity(city: self.currentCity)
                        
                        //存储当前城市
                        UserDefaults.standard.set(self.currentCity, forKey: currentCityKey)
                        // 结束存储
                        UserDefaults.standard.synchronize()
                    }
                    
                    self.initView()

                }
                
            })
        }
    }
  
    func initView(){
        self.navigationController?.navigationBar.isHidden = false
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        self.layoutNavigationBar(date:Tool.returnDate(date: NSDate()), weekDay: Tool.returnWeekDay(date: NSDate()), cityName: self.currentCity)
        
        self.request(cityName: self.currentCity)
        
        if self.myTableView == nil {
            self.automaticallyAdjustsScrollViewInsets = false
            self.myTableView = UITableView(frame: CGRect(x: 0, y: 44, width: self.view.bounds.size.width, height: self.view.bounds.size.height), style: .plain)
            self.view.addSubview(self.myTableView)
            
            // 下拉刷新
            self.myTableView.mj_header = header
            header.refreshingBlock = { () -> Void in
                self.layoutNavigationBar(date:Tool.returnDate(date: NSDate()), weekDay: Tool.returnWeekDay(date: NSDate()), cityName: self.currentCity)
                
                self.request(cityName: self.currentCity)
                
            }
            
            self.myTableView.delegate = self
            self.myTableView.dataSource = self
            let nib = UINib(nibName: "MainTableViewCell", bundle: Bundle.main)
            self.myTableView.register(nib, forCellReuseIdentifier: "reuseIdentifier")
            self.myTableView.rowHeight = 720
            
            self.myTableView.separatorStyle = .none
            self.myTableView.isHidden = true
            

        }
    }
    func layoutNavigationBar(date:String,weekDay:String,cityName:String){
        self.navigationController?.navigationBar.tintColor = UIColor.white
        let categoryBarItem = UIBarButtonItem(image: UIImage(named:"category_hover"), style: .plain, target: self, action: #selector(chooseDateAction))
        categoryBarItem.imageInsets = UIEdgeInsets(top: 4, left: 0, bottom: 0, right: 0)
        
        let dateBarItem = UIBarButtonItem(title: date + " " + weekDay, style:.plain, target: self, action: #selector(chooseDateAction))
        navigationItem.leftBarButtonItems = [categoryBarItem,dateBarItem]
        
        let sharedBarItem = UIBarButtonItem(image: UIImage(named:"share_small_hover"), style: .plain, target: self, action: #selector(sharedAction))
        
         let cityBarItem = UIBarButtonItem(title: cityName, style: .plain, target: self, action: nil)
        
         let settingBarItem = UIBarButtonItem(image: UIImage(named:"settings_hover"), style: .plain, target: self, action: #selector(settingAction))
        navigationItem.rightBarButtonItems = [settingBarItem,cityBarItem,sharedBarItem]
        
    }
    
    func request(cityName:String){
        let session = URLSession.shared
        let urlString = "http://api.k780.com:88/?app=weather.future&weaid=\(cityName)&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        let url = URL(string: urlString!)
        let task = session.dataTask(with: url!) { (data, response, error) in
            if error == nil {
                let weatherInfo = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
                let array = weatherInfo?["result"] as! NSArray
                let dic = array[0] as! NSDictionary
                
                self.currentWeatherInfo = WeatherInfo(dic: dic)
                
                DispatchQueue.main.async {
                    self.view.backgroundColor = Tool.returnWeatherBgColor(weatherType: self.currentWeatherInfo.weather!)
                    
                    self.myTableView.backgroundColor = Tool.returnWeatherBgColor(weatherType: self.currentWeatherInfo.weather!)
                    
                    self.navigationController?.navigationBar.backgroundColor = Tool.returnWeatherBgColor(weatherType: self.currentWeatherInfo.weather!)
                    
                    self.myTableView.cellForRow(at: IndexPath(row: 0, section: 0))?.backgroundColor = Tool.returnWeatherBgColor(weatherType: self.currentWeatherInfo.weather!)
                    self.myTableView.isHidden = false
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: LeftControllerTypeChangeNotification), object: nil, userInfo:["data":array])
                    self.header.endRefreshing()
                    self.myTableView.reloadData()
                    
                    self.hud.hide(animated: true)
                    
                }
                
            }
        }
        task.resume()
    }
    func chooseDateAction(sender:UIBarButtonItem){
        
    }
    func sharedAction(sender:UIBarButtonItem){
        let alert = UIAlertController(title: "分享天气", message: "",preferredStyle: .actionSheet)
        let QQZoneAction = UIAlertAction(title: "分享到QQ空间", style: .default) { (action) in
            let dic = NSMutableDictionary()
            dic.ssdkSetupQQParams(byText: "测试", title: "小炮天气", url: URL(string: "http://www.baidu.com"), thumbImage:  Tool.getImageFromView(view: (self.navigationController?.view)!), image: Tool.getImageFromView(view: (self.navigationController?.view)!), type: .auto, forPlatformSubType: SSDKPlatformType.subTypeQZone)
            ShareSDK.share(.subTypeQZone, parameters: dic) { (state, userdata, contentEntity, error) in
                
            }
        }
        
       
    
        alert.addAction(QQZoneAction)
        let QQFriendAction = UIAlertAction(title: "分享到QQ好友", style: .default) { (action) in
            let dic = NSMutableDictionary()
            dic.ssdkSetupQQParams(byText: "测试", title: "小炮天气", url: nil, thumbImage:  Tool.getImageFromView(view: (self.navigationController?.view)!), image:  Tool.getImageFromView(view: (self.navigationController?.view)!), type: .auto, forPlatformSubType: SSDKPlatformType.subTypeQQFriend)
            ShareSDK.share(.subTypeQQFriend, parameters: dic) { (state, userdata, contentEntity, error) in
                
            }
        }
        alert.addAction(QQFriendAction)
        let WechatFriendAction = UIAlertAction(title: "分享到微信好友", style: .default) { (action) in
            let dic = NSMutableDictionary()
            
                dic.ssdkSetupWeChatParams(byText: "测试", title: "小炮天气", url: nil, thumbImage: nil, image:  Tool.getImageFromView(view: (self.navigationController?.view)!), musicFileURL: nil, extInfo: nil, fileData: UIImagePNGRepresentation( Tool.getImageFromView(view: (self.navigationController?.view)!)), emoticonData: nil, sourceFileExtension: "png", sourceFileData: UIImagePNGRepresentation( Tool.getImageFromView(view: (self.navigationController?.view)!)), type: .auto, forPlatformSubType: .subTypeWechatSession)
                ShareSDK.share(.subTypeWechatSession, parameters: dic) { (state, userdata, contentEntity, error) in
                
            }

        }
        alert.addAction(WechatFriendAction)
        let WechatCircleAction = UIAlertAction(title: "分享到微信朋友圈", style: .default) { (action) in
            let dic = NSMutableDictionary()
            
            dic.ssdkSetupWeChatParams(byText: "测试", title: "小炮天气", url: nil, thumbImage:  Tool.getImageFromView(view: (self.navigationController?.view)!), image:  Tool.getImageFromView(view: (self.navigationController?.view)!), musicFileURL: nil, extInfo: nil, fileData: UIImagePNGRepresentation( Tool.getImageFromView(view: (self.navigationController?.view)!)), emoticonData: nil, sourceFileExtension: "png", sourceFileData: UIImagePNGRepresentation( Tool.getImageFromView(view: (self.navigationController?.view)!)), type: .auto, forPlatformSubType: .subTypeWechatTimeline)
            ShareSDK.share(.subTypeWechatTimeline, parameters: dic) { (state, userdata, contentEntity, error) in
                
            }
            
        }
        alert.addAction(WechatCircleAction)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alert.addAction(cancelAction)
        self.rootController?.present(alert, animated: true, completion: nil)
        
    }
    func settingAction(sender:UIBarButtonItem){
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier") as! MainTableViewCell
        if self.currentWeatherInfo != nil{
            cell.messageImageView.image = Tool.returnMessageImage(curWeatherInfo: currentWeatherInfo)
            
            cell.weatherImageView.image = Tool.returnWeatherImage(weatherType: self.currentWeatherInfo.weather!)
            cell.weatherLabel.text = self.currentWeatherInfo.weather
            
            cell.currentTempLabel.text = self.currentWeatherInfo.temp_low!
            
            cell.rangeTempLabel.text = self.currentWeatherInfo.temperature

            
            cell.windLabel.text = self.currentWeatherInfo.winp
            
            cell.rangeHumiLabel.text = self.currentWeatherInfo.humi_low
            
            
        }

        return cell
    }
}









